import React from 'react';
import {Table, Card, Divider, Form, Input, Row, Col, Button, Modal, message} from 'antd';
import {connect} from 'dva';
import {ColumnProps, TableProps} from 'antd/es/table';
import {PageHeaderWrapper} from '@ant-design/pro-layout';
import {FormComponentProps} from 'antd/es/form';
import {ModelState} from './model';
import {Dispatch} from 'redux';
import SaveModal from './components/save';
import PermissionAssignModal from './components/permissionAssign';
import {IRole} from '@/pages/account/role/data';
import {fetchAllMenus, fetchRoleMenus} from '@/pages/account/role/list/service';

interface IProps extends FormComponentProps {
  roleList: ModelState;
  loading: boolean;
  dispatch: Dispatch<any>;
}

interface IStates {
  selectedRowKeys: any[];
  formValues: object;
  saveModalVisible: boolean;
  permissionAssignModalVisible: boolean;

  roleInfo: IRole;
  allMenus: any[];
  roleMenus: any[];
}

class Index extends React.Component<IProps, IStates> {
  state: IStates = {
    selectedRowKeys: [],
    formValues: {},
    saveModalVisible: false,
    permissionAssignModalVisible: false,
    roleMenus: [],
    allMenus: [],
    roleInfo: {},
  };

  saveInstance: any = null;
  permissionInstance: any = null;

  tableColumns: ColumnProps<{}>[] = [
    {
      title: '名称',
      dataIndex: 'title',
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
    },
    {
      title: '操作',
      render: (text: any, record: any) => {
        return (
          <>
            <a
              onClick={() => {
                this.setState({
                  saveModalVisible: true,
                });
                this.saveInstance.props.form.setFieldsValue({
                  id: record.id,
                  title: record.title,
                });
              }}
            >
              编辑
            </a>
            <Divider type="vertical"/>
            <a
              onClick={() => {
                return this.assignMenus(record);
              }}
            >
              分配
            </a>
            <Divider type="vertical"/>
            <a
              onClick={() => {
                this.batchDelete(record.id);
              }}
            >
              删除
            </a>
          </>
        );
      },
    },
  ];

  componentDidMount() {
    const {dispatch} = this.props;
    dispatch({
      type: 'roleList/fetch',
    });
  }

  tableChange: TableProps<{}>['onChange'] = (pagination, filters, sorter, extra) => {
    const {dispatch} = this.props;
    const {formValues} = this.state;
    const params = {
      ...formValues,
      ...pagination,
    };

    dispatch({
      type: 'roleList/fetch',
      payload: params,
    });
  };

  assignMenus = async (role: IRole) => {
    const stateData = {permissionAssignModalVisible: true};
    const hide = message.loading('正在加载权限数据...', 0);

    if (this.state.allMenus.length === 0) {
      const allMenusResult = await fetchAllMenus();
      stateData["allMenus"] = allMenusResult.data
    }
    const {data: roleMenusData} = await fetchRoleMenus({id: role.id});
    hide();
    this.permissionInstance.props.form.setFieldsValue({
      menus: roleMenusData.map((item: any) => item.id),
      roleId: role.id
    });
    this.setState(stateData);
  };

  searchSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    const {form, dispatch} = this.props;
    form.validateFields((err, fieldsValue) => {
      const values = {...fieldsValue};

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'roleList/fetch',
        payload: values,
      });
    });
  };

  resetFrom = () => {
    const {form, dispatch} = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'roleList/fetch',
      payload: {},
    });
  };

  //批量删除or单个删除
  batchDelete = (id = null) => {
    let ids: any[] = [];
    let title: string;
    if (!id) {
      ids = this.state.selectedRowKeys;
      title = '批量删除角色';
    } else {
      ids = [id];
      title = '删除角色';
    }

    const {dispatch} = this.props;
    Modal.confirm({
      title: title,
      content: '您确认要删除所选角色吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        if (ids.length === 0) {
          message.warning('请先选择你要删除的选项');
          return;
        }
        dispatch({
          type: 'roleList/batchDelete',
          payload: {ids: ids},
        });
      },
    });
  };

  permissionAssignModalOk = (params: { id: number; menus: number[] }) => {
    const {dispatch} = this.props;
    dispatch({
      type: 'roleList/saveMenus',
      payload: params,
      callback: () => {
        this.setState({
          permissionAssignModalVisible: false,
        });
      },
    });
  };
  saveModalCancel = () => {
    this.setState({
      saveModalVisible: false,
    });
  };

  saveModalOk = ({id, title}: IRole) => {
    const {dispatch} = this.props;
    dispatch({
      type: 'roleList/addOrUpdate',
      payload: {id, title},
      callback: () => {
        this.saveModalCancel();
      },
    });
  };

  render() {
    const {selectedRowKeys, saveModalVisible, permissionAssignModalVisible} = this.state;
    const {form, roleList: {data}, loading} = this.props;

    const getFieldDecorator = form.getFieldDecorator;

    const rowSelection = {
      selectedRowKeys: selectedRowKeys,
      onChange: (selectedRowKeys: any[], selectedRows: any[]) => {
        this.setState({
          selectedRowKeys: selectedRowKeys,
        });
      },
    };

    return (
      <PageHeaderWrapper title={false}>
        <Card bordered={false}>
          <Form layout="inline" onSubmit={this.searchSubmit}>
            <Row>
              <Col span={10}>
                <Button
                  type="primary"
                  onClick={() => {
                    this.setState({
                      saveModalVisible: true,
                    });
                    this.saveInstance.props.form.setFieldsValue({
                      title: '',
                      id: 0,
                    });
                  }}
                >
                  新增
                </Button>
                <Button
                  type="danger"
                  style={{marginLeft: 10}}
                  onClick={() => {
                    this.batchDelete(null);
                  }}
                >
                  删除
                </Button>
              </Col>
              <Col span={14}>
                <div style={{float: 'right'}}>
                  <Form.Item>
                    {getFieldDecorator('keyword', {})(
                      <Input placeholder="请输入角色标题" {...{}} style={{width: 250}}/>,
                    )}
                  </Form.Item>
                  <Button type="primary" style={{marginTop: 4}} htmlType="submit">
                    查询
                  </Button>
                  <Button type="dashed" style={{margin: '4px 0 0 5px'}} onClick={this.resetFrom}>
                    重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
          <Divider/>
          <Table
            loading={loading}
            rowKey="id"
            columns={this.tableColumns}
            dataSource={data.list}
            pagination={data.pagination}
            rowSelection={rowSelection}
            onChange={this.tableChange}
            {...{}}
          />
        </Card>
        <SaveModal
          wrappedComponentRef={(form: any) => (this.saveInstance = form)}
          visible={saveModalVisible}
          onCancel={this.saveModalCancel}
          onOk={this.saveModalOk}
        />
        <PermissionAssignModal
          wrappedComponentRef={(form: any) => (this.permissionInstance = form)}
          visible={permissionAssignModalVisible}
          onCancel={() => {
            this.setState({permissionAssignModalVisible: false});
          }}
          onOk={this.permissionAssignModalOk}
          allMenus={this.state.allMenus}
        />
      </PageHeaderWrapper>
    );
  }
}

export default Form.create<IProps>()(
  connect(
    ({
       roleList,
       loading,
     }: {
      roleList: ModelState;
      loading: {
        models: {
          [key: string]: boolean;
        };
      };
    }) => ({
      roleList,
      loading: loading.models.roleList,
    }),
  )(Index),
);
